/***
 *
 * 特定布局结构的代码包装：
 * - 布局结构
 * <div id="application"></div>
 *  <!-- 整体布局 -->
 *    <script type="text/x-kendo-template" id="layout-template">
 *        <%--  导航头 --%>
 *        <div id="header" class='bg-primary'></div>
 *        <%--  面包屑 --%>
 *        <div id="breadcrumb" class="container-fluid"></div>
 *        <!-- 主体 -->
 *        <div id="main-section" class="container-fluid">
 *            <div class="sidebar-left" id="menu"></div><%--  左侧菜单 --%>
 *               <div class="container-right-wrap"><%--  右区 --%>
 *                <div class="sidebar-show"><i class="icon icon-caret-left"></i></div>
 *                <div id="detail" class="container container-right" ></div>
 *            </div>
 *            <div class="container-nav" id="content"> <%--  内容显示区 --%>
 *            </div>
 *        </div>
 *     </script>
 *
 *    <%--  导航头模板 --%>
 *    <script id="header-template" type="text/x-kendo-template">
 *        <%@ include file="/_template/header.jsp" %>
 *    </script>
 *    <%--  面包屑模板 --%>
 *    <script id="crumb-template" type="text/x-kendo-template">
 *        <ol class="breadcrumb" data-bind="source:crumbItems" data-template="crumb-item-template"></ol>
 *    </script>
 *    <script id="crumb-item-template" type="text/x-kendo-template">
 *        <li><a href="javascript:" data-bind="text:name"></a></li>
 *    </script>
 *   <%--  左边菜单模板 --%>
 *    <script id="menu-template" type="text/x-kendo-template">
 *        <%@ include file="/_template/menu.jsp" %>
 *    </script>
 *
 * - 示例
 * (function(){
 *    var views = [
 *                {
 *                    id: "searchCustom",
 *                    title: '',
 *                    hash: "#content",
 *                    url: '_view_custom_init.html',
 *                }
 *     ];
 *     var app = new front.App();
 *     app.init(
 *                "/api/page_init/hr_report/hr_report_query"
 *                 views,
 *                 function (router, lay) {
 *                       router.route("/", function () {
 *                               lay.showInById('searchCustom');
 *                       })
 *            );
 *
 * })()
 *
 * @returns {
 *    front.App
 * }
 * @constructor
 *
 */
front.App = function (appData) {
    var router = null;
    var lay = null;
    var that = this
    var path = {};

    /***
     * 显示页面头、面包屑、菜单
     */
    function showAlways() {
        lay.showInById("header");
        lay.showInById("breadcrumb");
        lay.showInById("menu");
    }

    /**
     * 依据路径后缀，选中菜单
     *
     * @param hash
     * @returns {*}
     */
    function selectMenuItem(hash) {
        if (hash == '/') {
            hash = '/index.jsp';
        }
        var menuItems = that.appData.menuItems;
        for (var i = 0; i < menuItems.length; ++i) {
            var items = menuItems[i].items || [];
            var found = _.find(items, function (item) {
                return _.endsWith(item.url, hash);
            })
            if (found) {
                _.forEach(items, function (it) {
                    it.selected = false;
                });
                found.selected = true;
                return found;
            }
        }
        return undefined;
    }

    //显示菜单项
    var tnLi = function (node) {
        var hasItems = node.items ? true : false
        if (node.name.length > 10) {
            var s = hasItems ? '<li class="active show nav-parent"><a href="javascript:;"><i class="' + node.icon + '"></i>' + node.name + '<i class="icon-chevron-right nav-parent-fold-icon"></i></a>' :
                '<li><a class="funcMenu" title="' + node.name + '" href="' + node.url + '" data-code="' + node.code + '"><i class="' + node.icon + '"></i>' + node.name + '</a>';
            if (node.selected == true) {
                s = hasItems ? '<li class="active show nav-parent"><a href="javascript:;"><i class="' + node.icon + '"></i>' + node.name + '<i class="icon-chevron-right nav-parent-fold-icon"></i></a>' :
                    '<li><a class="funcMenu" title="' + node.name + '" href="' + node.url + '" data-code="' + node.code + '"><i class="' + node.icon + '"></i>' + node.name + '</a>';
            }
        } else {
            var s = hasItems ? '<li class="active show nav-parent"><a href="javascript:;"><i class="' + node.icon + '"></i>' + node.name + '<i class="icon-chevron-right nav-parent-fold-icon"></i></a>' :
                '<li><a class="funcMenu" href="' + node.url + '" data-code="' + node.code + '"><i class="' + node.icon + '"></i>' + node.name + '</a>';
            if (node.selected == true) {
                s = hasItems ? '<li class="active show nav-parent"><a href="javascript:;"><i class="' + node.icon + '"></i>' + node.name + '<i class="icon-chevron-right nav-parent-fold-icon"></i></a>' :
                    '<li class="active"><a class="funcMenu" href="' + node.url + '" data-code="' + node.code + '"><i class="' + node.icon + '"></i>' + node.name + '</a>';
            }
        }

        if (hasItems) {
            s += '<ul class="nav">'
            _.each(node.items, function (it) {
                s += tnLi(it)
            })
            s += '</ul>'
        }
        s += '</li>'
        return s;
    }

    this.appData = appData;

    /**
     * 返回lay对象
     * @returns {*}
     */
    this.getlay = function () {
        return lay;
    }
    /***
     * 返回router对象，此对象是kendo对象
     * @returns {*}
     */
    this.getRouter = function () {
        return router;
    }
    /**
     * 提供导航方法封装
     *
     * @param path
     */
    this.navigate = function (path) {
        router.navigate(path);
    }
    /***
     * 进行页面初始化
     *
     * @param url
     *      此url获取的数据包含导航数据、菜单结构数据、用户profile数据，
     *      视图将显示这些数据
     *
     * @param views
     *      此页面的视图数组，元素是视图配置对象 @see front.layout.Layout
     *
     * @param onInitAfter
     *      页面初始化后执行的函数
     *
     * @param showFuncs
     *      页面整体显示后执行的函数
     *
     */
    this.init = function (url, views, onInitAfter, showFuncs) {
        var opts =
            {
                el: "layout-template", //布局视图标识符
                //定义视图
                views: [
                    {
                        id: 'header',
                        title: '导航头',
                        hash: "#header",
                        template: 'header-template',
                        model: kendo.observable({
                            navItems: []
                        }),
                        init: function () {

                        }
                    },
                    {
                        id: 'breadcrumb',
                        title: '面包屑',
                        hash: '#breadcrumb',
                        template: 'crumb-template',
                        type: 'local',
                        model: kendo.observable({
                            crumbItems: []
                        })
                    },
                    {
                        id: 'menu',
                        title: '左侧菜单',
                        hash: '#menu',
                        template: 'menu-template',
                        model: kendo.observable({
                            menuItems: [],
                            gotoNew: function (e) {
                                e.preventDefault();
                                router.navigate("/fld_tree");
                            }
                        }),
                        init: function () {
                            $('#app-menu').menu({auto: true});
                        }
                    }]
            }
        opts.views = opts.views.concat(views);
        lay = new front.layout.Layout(opts);
        router = new kendo.Router({
            init: function () {
                lay.getLayout().render("#application");
            }
        });
        front.ajax.getFetch({
            url: url,
        }).done(function (result) {
            if (result.status != 'ok') {
                layer.msg(result.message)
                return
            }

            that.appData = that.appData || result.data;
            var menuHtml = that.buildMenu();

            var profile = result.data.profile || {};

            var appIcon = profile.appIcon;
            var appTitle = profile.appTitle;

            var notificationNum = profile.notificationNum;

            if (notificationNum && notificationNum != '0') {
                notificationNum = kendo.format('<span class="label label-badge">{0}</span>', notificationNum);
            }
            else {
                notificationNum = '';
            }

            if (appTitle && appTitle != '') {
            } else {
                appTitle = "数据转换平台";
            }
            if (appIcon && appIcon != '') {
                appIcon = window.ctxStatic + appIcon;
            } else {
                appIcon = window.ctxStatic + "/images/pds-logo.png";
            }
            var href = window.location.href;

            _.each(result.data.navItems, function (it) {
                //if (href.indexOf(it.url) != -1) {
                if (it.selected) {
                    it.class_name = 'active'
                } else {
                    it.class_name = ''
                }
            });

            $(document).attr("title", appTitle);//修改title值

            lay.findModel('header').set('navItems', result.data.navItems)
            lay.findModel('header').set('realName', result.data.realName)
            lay.findModel('header').set('appTitle', appTitle)
            lay.findModel('header').set('appIcon', appIcon)
            lay.findModel('header').set('notificationNum', notificationNum)
            lay.findModel('menu').set('menuItems', menuHtml)
            lay.findModel('breadcrumb').set('crumbItems', result.data.crumbItems)

            onInitAfter ? onInitAfter(router, lay):null;

            router.start();
            showAlways();

            showFuncs ? showFuncs(router, lay) : null
            return that;
        })
    }
    this.biz = {};

    this.resetCrumbItems = function (hash, after) {
        var crumbItems = that.appData.crumbItems;
        var other = _.concat([], crumbItems);
        var found = selectMenuItem(hash);
        if (found) {
            other[crumbItems.length - 1] = found;
        }
        after && after(other);
    }

    this.buildMenu = function () {
        var menuHtml = '';
        var menuItems = that.appData.menuItems;
        _.each(menuItems, function (it) {
            menuHtml += tnLi(it)
        });
        return menuHtml;
    }

    return that;
};
